import React, { useEffect, useState } from 'react';
import { Table, Space, Modal, message, Checkbox, Button } from 'antd';
import axios from 'axios';

const MenuManagement = () => {
    const [permissions, setPermissions] = useState([]);
    const [allRoles, setAllRoles] = useState([]);
    const [permissionRoles, setPermissionRoles] = useState({});
    const [selectedPermissionsIds, setSelectedPermissionsIds] = useState([52, 53, 54, 55, 56, 57, 58, 59, 60]); // 指定的权限ID数组

    useEffect(() => {
        const currentUser = JSON.parse(localStorage.getItem('currentUser'));
        const token = currentUser?.token;
        if (token) {
            axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
            console.log('设置 Authorization 头:', `Bearer ${token}`);
        } else {
            console.error('未在 currentUser 中找到 token');
        }
        fetchPermissionsWithRoles();
        fetchAllRoles();
    }, []);

    // 获取所有角色信息
    const fetchAllRoles = async () => {
        try {
            const response = await axios.get(`http://localhost:8080/api/roles/get-all-roles-with-permissions`);
            const data = response.data;

            if (response.status === 200 && data.code === 200) {
                setAllRoles(data.data);
                console.log('获取所有角色信息成功:', data.data);
            } else {
                message.error(data.message || '获取角色信息失败，请稍后再试！');
            }
        } catch (error) {
            console.error('获取角色信息失败:', error);
            message.error(error.response?.data?.message || '获取角色信息失败，请稍后再试！');
        }
    };

    // 获取指定权限及其关联的角色
    const fetchPermissionsWithRoles = async () => {
        try {
            const response = await axios.post(`http://localhost:8080/api/roles/get-permissions-with-roles`, selectedPermissionsIds);
            const data = response.data;

            if (response.status === 200 && data.code === 200) {
                setPermissions(data.data.permissions);

                // 构建 permissionRoles 对象
                const permissionRolesMap = {};
                data.data.permissions.forEach(permission => {
                    permissionRolesMap[permission.permissionId] = permission.roleIds || [];
                });
                setPermissionRoles(permissionRolesMap);
                console.log('获取权限及其关联的角色成功:', data.data);
            } else {
                message.error(data.message || '获取权限信息失败，请稍后再试！');
            }
        } catch (error) {
            console.error('获取权限信息失败:', error);
            message.error(error.response?.data?.message || '获取权限信息失败，请稍后再试！');
        }
    };

    // 添加角色到权限
    const handleAddRoleToPermission = async (permissionId, roleId) => {
        try {
            const payload = { permissionId, roleId };
            const response = await axios.post('http://localhost:8080/api/roles/add-role', payload);
            const data = response.data;

            if (response.status === 200 && data.code === 200) {
                message.success(data.message);
                await fetchPermissionsWithRoles(); // 刷新数据

                // 更新本地状态
                const updatedPermissionRoles = { ...permissionRoles };
                updatedPermissionRoles[permissionId] = [...(updatedPermissionRoles[permissionId] || []), roleId];
                setPermissionRoles(updatedPermissionRoles);
            } else {
                message.error(data.message || '添加角色失败，请稍后再试！');
            }
        } catch (error) {
            console.error('更新权限失败:', error);
            message.error(error.response?.data?.message || '添加角色失败，请稍后再试！');
        }
    };

    // 移除角色从权限
    const handleRemoveRoleFromPermission = async (permissionId, roleId) => {
        try {
            const payload = { permissionId, roleId };
            const response = await axios.post('http://localhost:8080/api/roles/remove-role', payload);
            const data = response.data;

            if (response.status === 200 && data.code === 200) {
                message.success(data.message);
                await fetchPermissionsWithRoles(); // 刷新数据

                // 更新本地状态
                const updatedPermissionRoles = { ...permissionRoles };
                updatedPermissionRoles[permissionId] = updatedPermissionRoles[permissionId].filter(id => id !== roleId);
                setPermissionRoles(updatedPermissionRoles);
            } else {
                message.error(data.message || '移除角色失败，请稍后再试！');
            }
        } catch (error) {
            console.error('更新权限失败:', error);
            message.error(error.response?.data?.message || '移除角色失败，请稍后再试！');
        }
    };

    const columns = [
        {
            title: 'ID',
            dataIndex: 'permissionId',
            key: 'permissionId'
        },
        {
            title: '菜单名称',
            dataIndex: 'permissionName',
            key: 'permissionName',
            render: (text) => text.replace('menu访问-', '') // 去掉前缀
        },
        {
            title: '可访问的角色',
            key: 'roles',
            render: (text, record) => (
                <Space size="middle">
                    {allRoles.map(role => (
                        <Checkbox
                            key={role.roleId}
                            checked={permissionRoles[record.permissionId]?.includes(role.roleId)}
                            onChange={(e) => e.target.checked ? handleAddRoleToPermission(record.permissionId, role.roleId) : handleRemoveRoleFromPermission(record.permissionId, role.roleId)}
                        >
                            {role.roleName}
                        </Checkbox>
                    ))}
                </Space>
            )
        }
    ];
    // 在返回 JSX 之前对 permissions 进行排序
    const sortedPermissions = permissions.slice().sort((a, b) => a.permissionId - b.permissionId);

    return (
        <div>
            <h2>菜单访问权限管理</h2>
            <Table
                dataSource={sortedPermissions}
                columns={columns}
                rowKey="permissionId"
                pagination={false}
                bordered
            />
        </div>
    );
};

export default MenuManagement;